import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/userInfo")
public class UserInfoServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户信息
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        String blogId = req.getParameter("blogId");

        if (blogId == null){
            // 列表页 获取当前登录用户的信息
            getUserInfoFromSession(req,resp);
        }else{
            try {
                getUserInfoFromDB(req,resp,Integer.parseInt(blogId));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void getUserInfoFromDB(HttpServletRequest req, HttpServletResponse resp, int blogId) throws SQLException, IOException {
        // 1. 根据blogId 查询blog对象 获取userId
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(blogId);
        if (blog == null){
            resp.setContentType("text/html; charset=utf8");
            resp.setStatus(404);
            resp.getWriter().write("当前 blogId 未找到!");
            return;
        }
        // 2. 根据userId 获取对应的user
        UserDao userDao = new UserDao();
        User user = userDao.selectById(blog.getUserId());
        if (user == null){
            resp.setContentType("text/html; charset=utf8");
            resp.setStatus(404);
            resp.getWriter().write("当前 blogId 未找到!");
            return;
        }
        // 将user的密码置为空, 防止发送请求时,密码泄露
        user.setPassword("");
        resp.setContentType("application/json");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }

    private void getUserInfoFromSession(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession(false);

        if (session == null){
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录!");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null){
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录!");
            return;
        }
        // 将用户的密码置为空,然后发送请求
        user.setPassword("");
        resp.setContentType("application/json");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
